﻿using RabbitMQ.Client.Events;
using RabbitMQ.Client;
using System.Text;

namespace DLXSubsriber
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var factory = new ConnectionFactory() { HostName = "localhost" };
            var connection = factory.CreateConnection();
            var channel = connection.CreateModel();
            channel.QueueDeclare(queue: "task_queue", durable: true, exclusive: false, autoDelete: false, arguments: new Dictionary<string, object>
            {
                { "x-dead-letter-exchange","dlx_task_exchange" },
                { "x-dead-letter-routing-key","dlx_task_routingKey" },
            });
            channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);
            Console.WriteLine("[*] Waiting for messages.");
            var consumer = new EventingBasicConsumer(channel);
            consumer.Received += (sender, ea) =>
            {
                var body = ea.Body.ToArray();
                var message = Encoding.UTF8.GetString(body);
                ((EventingBasicConsumer)sender).Model.BasicNack(deliveryTag: ea.DeliveryTag, multiple: false, requeue: false);
            };
            channel.BasicConsume(queue: "task_queue", autoAck: false, consumer: consumer);

            var channel1 = connection.CreateModel();
            channel1.ExchangeDeclare(exchange: "dlx_task_exchange", type: "direct");
            channel1.QueueDeclare(queue: "dlx_task_queue", durable: false, exclusive: false, autoDelete: false);
            channel1.QueueBind(queue: "dlx_task_queue", exchange: "dlx_task_exchange", routingKey: "dlx_task_routingKey");

            var consumer1 = new EventingBasicConsumer(channel1);
            consumer1.Received += (sender, ea) =>
            {
                var body = ea.Body.ToArray();
                var message = Encoding.UTF8.GetString(body);
                //取消订单的操作，（判断是否支付）
                Console.WriteLine($"[x] 收到 死信队列消息 {message}");
                ((EventingBasicConsumer)sender).Model.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
            };
            channel1.BasicConsume(queue: "dlx_task_queue", autoAck: false, consumer: consumer1);
            Console.ReadLine();
        }
    }
}